<template>
  <page-header-wrapper>
    <a-card>
      {%- set ns = namespace(has_searchable=false) -%}
      {%- for field_name, field in columns.items() -%}
      {%- if field.mark.searchable is defined -%}
      {%- set ns.has_searchable = true -%}
      {%- endif -%}
      {%- endfor -%}

      {%- if ns.has_searchable %}
      <AnypaySearchForm :searchFunc="searchFunc" :resetFunc="resetSearch">
        {%- for field_name, field in columns.items() -%}
        {%- if field.mark.searchable -%}
        {%- if field.mark.searchable.type == 'like' %}
        <anypay-text-up v-model:value="searchData.{{ field.naming.field_name }}" placeholder="{{ field.common.label }}" />
        {%- elif field.mark.searchable.type == 'equal' -%}
        {%- if field.mark.enum_options %}
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="searchData.{{ field.sql.name }}" placeholder="{{ field.common.label }}">
            <a-select-option value="">全部</a-select-option>
            {%- for option in field.mark.enum_options %}
            <a-select-option value="{{ option.value }}">{{ option.label }}</a-select-option>
            {%- endfor %}
          </a-select>
        </a-form-item>
        {%- else %}
        <anypay-text-up v-model:value="searchData.{{ field.sql.name }}" placeholder="{{ field.common.label }}" />
        {%- endif -%}
        {%- elif field.mark.searchable.type == 'range' %}
        <!-- TODO: 支持range类型搜索 -->
        {%- endif -%}
        {%- endif -%}
        {%- endfor %}
      </AnypaySearchForm>
      {%- endif %}

      <AnypayTable
        ref="itemTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="searchData"
        rowKey="id"
        @btnLoadClose="btnLoading = false"
      >
        <template #topBtnSlot>
          <div>
            <a-button type="primary" class="mg-b-30" @click="addItem">
              <plus-outlined /> 新增{{ table.common.label }}
            </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          {%- for field_name, field in columns.items() -%}
          {%- if field.mark.enum_options %}
          <template v-if="column.key === '{{ field.naming.field_name }}'">
            {%- if field.sql.name == 'gender' %}
            {{ '{{' }} record.{{ field.naming.field_name }} === 'M' ? '男' : '女' {{ '}}' }}
            {%- else %}
            <a-tag>
              {%- for option in field.mark.enum_options %}
              {{ '{{' }} record.{{ field.naming.field_name }} === '{{ option.value }}' ? '{{ option.label }}' : '' {{ '}}' }}
              {%- endfor %}
            </a-tag>
            {%- endif %}
          </template>
          {%- endif -%}
          {%- endfor %}
          <template v-if="column.key === 'op'">
            <AnypayTableColumns>
              <a-button type="link" @click="editItem(record)">编辑</a-button>
              <a-button type="link" @click="viewItem(record)">查看</a-button>
              <a-button type="link" style="color: red" @click="deleteItem(record.id)">删除</a-button>
            </AnypayTableColumns>
          </template>
        </template>
      </AnypayTable>
    </a-card>

    <{{ table.derived.naming.class_name }}AddOrEditDrawer
      ref="addOrEditDrawRef"
      :callbackFunc="searchFunc"
    />

    <{{ table.derived.naming.class_name }}DetailDrawer ref="detailDrawerRef" />
  </page-header-wrapper>
</template>

<script lang="ts" setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { api{{ table.derived.naming.class_name }}FetchList, api{{ table.derived.naming.class_name }}Delete } from "./api";
import {{ table.derived.naming.class_name }}DetailDrawer from "./Detail.vue";
import {{ table.derived.naming.class_name }}AddOrEditDrawer from "./AddOrEdit.vue";

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties;

// 搜索条件
const searchData = reactive<{
  {%- for field_name, field in columns.items() -%}
  {%- if field.mark.searchable %}
  {{ field.naming.field_name }}: string;
  {%- endif -%}
  {%- endfor %}
}>({
  {%- for field_name, field in columns.items() -%}
  {%- if field.mark.searchable %}
  {{ field.naming.field_name }}: "",
  {%- endif -%}
  {%- endfor %}
});

// 表格列定义
const tableColumns = reactive([
  {%- for field_name, field in columns.items() %}
  { key: "{{ field.naming.field_name }}", title: "{{ field.common.label }}", dataIndex: "{{ field.naming.field_name }}" },
  {%- endfor %}
  { key: "op", title: "操作", fixed: "right", align: "center" },
]);

// 组件引用
const itemTable = ref();
const addOrEditDrawRef = ref();
const detailDrawerRef = ref();
const btnLoading = ref(false);

// 表格数据加载
async function reqTableDataFunc(params: any) {
  try {
    const ret = await api{{ table.derived.naming.class_name }}FetchList(params);
    return ret.data;
  } catch (error) {
    console.error('Failed to fetch data list:', error);
    return { records: [], total: 0 };
  }
}

// 搜索和重置
function searchFunc() {
  itemTable.value?.refTable(true);
}

function resetSearch() {
  {%- for field_name, field in columns.items() -%}
  {%- if field.mark.searchable %}
  searchData.{{ field.naming.field_name }} = "";
  {%- endif -%}
  {%- endfor %}
  itemTable.value?.refTable(true);
}

// CRUD操作
function addItem() {
  addOrEditDrawRef.value?.show(null);
}

function editItem(item: any) {
  addOrEditDrawRef.value?.show(item);
}

function viewItem(item: any) {
  detailDrawerRef.value?.openDrawer(item);
}

function deleteItem(itemId: number) {
  $infoBox.confirmDanger('确认删除该{{ table.common.label }}信息？', '', () => {
    api{{ table.derived.naming.class_name }}Delete(itemId).then(() => {
      $infoBox.message.success('删除成功');
      searchFunc();
    });
  });
}
</script>